package com.tedu.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tedu.model.Address;
import com.tedu.model.Cart;
import com.tedu.model.Order;
import com.tedu.model.OrderProduct;
import com.tedu.model.Product;
import com.tedu.model.User;
import com.tedu.service.IAddressService;
import com.tedu.service.ICartService;
import com.tedu.service.IOrderProductService;
import com.tedu.service.IOrderService;
import com.tedu.service.IProductService;
import com.tedu.service.IUserService;
import com.tedu.util.CodeUtil;

@Controller
@RequestMapping("/order")
public class OrderController {
	private IAddressService addressService;
	private IOrderService orderService;
	private IOrderProductService orderProductService;
	private IProductService productService;
	private ICartService cartService;
	private IUserService userService;
	@Resource
	public void setAddressService(IAddressService addressService) {
		this.addressService = addressService;
	}
	@Resource
	public void setOrderService(IOrderService orderService) {
		this.orderService = orderService;
	}
	@Resource
	public void setOrderProductService(IOrderProductService orderProductService) {
		this.orderProductService = orderProductService;
	}
	@Resource
	public void setProductService(IProductService productService) {
		this.productService = productService;
	}
	@Resource
	public void setCartService(ICartService cartService) {
		this.cartService = cartService;
	}
	@Resource
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}


 /**
     * 后台显示订单
     */
    @RequestMapping(value="/admin_order/{status}", method=RequestMethod.GET)
	public String list(@PathVariable int status, Model model) {
    	
		List<Order> orders = orderService.adminlist(status);
		model.addAttribute("orders", orders);
		return "admin/order/list";
	}
    
    /**
     * 修改订单状态
     */
    @RequestMapping(value="/adupdate_order/{id}/{status}", method=RequestMethod.PUT)
	public String updateStatus(@PathVariable int id,@PathVariable int status, Model model) {
    	Order order = orderService.load(id);
    	order.setStatus(status);
		orderService.update(order);
		
		return "redirect:/order/admin_order/2";
	}
    /**
     * 搜索订单
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping(value="/adminsearch_order", method=RequestMethod.GET)
	public String searchOrder(HttpServletRequest request, Model model) throws UnsupportedEncodingException {
    	/*byte[] name = request.getParameter("str").getBytes("ISO-8859-1");
    	String str =  new String(name,"UTF-8") ;
*/   
    	String str = request.getParameter("str");
    	System.out.println(str);
    	List<Order> orders = orderService.adminsearch(str);
		model.addAttribute("orders", orders);
		return "admin/order/list";
	}

		
	/**前台
	 * 创建订单操作 -- 立即购买和购物车结算操作
	 * 创建的订单初始状态是"未付款状态",不修改商品库存和商品销量
	 */
	@RequestMapping(value="/create_order", method=RequestMethod.POST)
	public String createOrder(Integer aid, String cids, double price, String base, String place, 
		String name, String phone, HttpSession session, Model model) {
		User loginUser = (User) session.getAttribute("loginUser");
		//判断用户是否登录
		if(loginUser == null) {
			return "redirect:/user/login";
		}
		Address address = null;
		//如果是新添加的地址,保存到数据库中
		if(base != null && place != null && name != null && phone != null) {
			address = new Address(base, place, name, phone, 1, loginUser);
			addressService.add(address);
		}
		else {
			address = addressService.load(aid);
		}
		//新创建的订单是"未付款"状态
		int status = 1;
		//新创建的订单是"未删除"状态
		int isdel = 1;
		//获取系统时间
		
		Date d = new Date();
		//格式化时间
		String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
		//时间转换
		Timestamp date = Timestamp.valueOf(nowTime);
		//创建订单
		Order order = new Order(price, status, isdel, date, address, loginUser);
		//保存订单
		orderService.add(order);
		//获取所有的购物车id
		String carts[] = cids.split(",");
		/**
		 * 由于第一个存放在数组中的第一个值为空,因此舍弃数组中的第一个元素
		 */
		for(int i = 1; i < carts.length; i++) {
			//获取购物车记录
			Cart cart = cartService.load(Integer.parseInt(carts[i]));
			//获取购物车中的商品
			Product product = cart.getProduct();
			//创建订单商品关系
			OrderProduct orderProduct = new OrderProduct(cart.getQuantity(), order, product);
			//保存订单与商品关系
			orderProductService.add(orderProduct);
			//删除购物车中的记录
			cartService.delete(Integer.parseInt(carts[i]));
			//获取登录用户的购物车中商品种类数量
			int cartSize = cartService.cartSize(loginUser.getId());
			session.setAttribute("cartSize", cartSize); 
		}
		//获取数据库中订单详细信息
		Order o = orderService.load(order.getId());
		model.addAttribute(o);
		return "client/user/pay";
	}
	/**
	 * 订单支付操作
	 * 付款成功后,修改商品库存和商品销量
	 */
	@RequestMapping(value="/payment", method=RequestMethod.POST)
	public String payment(int oid, String password, Model model, HttpSession session) {
		//获取订单对象
		Order order = orderService.load(oid);
		System.out.println(order.getAddress() + "--------------------");
		User loginUser = (User) session.getAttribute("loginUser");
		//密码输入有误
		if(!CodeUtil.getMD5Encoding(password).equals(loginUser.getPassword())) {
			model.addAttribute(order);
			model.addAttribute("errormsg", "*密码有误，请输入正确的密码完成支付");
			return "client/user/pay";
		}
		else {
			//获取订单对应的订单与商品关系
			List<OrderProduct> orderProducts = order.getOrderProducts();
			for(OrderProduct orderProduct:orderProducts) {
				Product product = orderProduct.getProduct();
				//修改商品库存
				product.setInventory(product.getInventory() - orderProduct.getQuantity());
				//修改商品销量
				product.setSales(product.getSales() + orderProduct.getQuantity());
				productService.update(product);
			}
			//修改个人账户余额    已经去除
		
			//清除session中的记录
			session.removeAttribute("cartIds");
			//订单状态修改为已付款
			order.setStatus(2);
			orderService.update(order);
			model.addAttribute(order);
			return "client/user/pay_success";
		}
	}
	/**
	 * 查看我的订单
	 */
	@RequestMapping(value="/my_order/{status}", method=RequestMethod.GET)
	public String myOrder(@PathVariable int status, Model model, HttpSession session) {
		User loginUser = (User) session.getAttribute("loginUser");
		//获取用户所有订单
		if(status == 0) {		
			//获取未付款订单数量
			int waitPay = orderService.countByStatus(loginUser.getId(), 1);
			//获取待发货订单数量
			int waitSend = orderService.countByStatus(loginUser.getId(), 2);
			//获取待收货订单数量
			int waitConfirm = orderService.countByStatus(loginUser.getId(), 3);
			//获取退款中订单数量
			int refund = orderService.countByStatus(loginUser.getId(), 4);
			//获取退款完成订单数量
			int refundSuccess = orderService.countByStatus(loginUser.getId(), 5);
			//获取完成的订单
			int orderSuccess = orderService.countByStatus(loginUser.getId(), 6);
			
			
			session.removeAttribute("waitPay");	
			session.removeAttribute("waitSend");
			session.removeAttribute("waitConfirm");
			session.removeAttribute("refund");
			session.removeAttribute("refundSuccess");
			session.removeAttribute("orderSuccess");
			
				
			if(waitPay > 0) {
				
				session.setAttribute("waitPay", waitPay);
			}
			if(waitSend > 0) {
				session.setAttribute("waitSend", waitSend);
			}
			if(waitConfirm > 0) {
				session.setAttribute("waitConfirm", waitConfirm);
			}
			if(refund > 0) {
				session.setAttribute("refund", refund);
			}
			if(refundSuccess > 0) {
				session.setAttribute("refundSuccess", refundSuccess);
			}
			if(orderSuccess > 0) {
				session.setAttribute("orderSuccess", orderSuccess);
			}
			
		
			List<Order> orders = orderService.list(loginUser.getId());
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
		//获取用户未付款订单
		if(status == 1) {
			
			
			List<Order> orders = orderService.listByStatus(loginUser.getId(), 1);
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
		//获取用户未发货订单
		if(status == 2) {
			List<Order> orders = orderService.listByStatus(loginUser.getId(), 2);
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
		//获取用户待收货订单
		if(status == 3) {
			List<Order> orders = orderService.listByStatus(loginUser.getId(), 3);
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
		//获取用户退款中订单
		if(status == 4) {
			List<Order> orders = orderService.listByStatus(loginUser.getId(), 4);
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
		//获取用户退款完成订单
		if(status == 5) {
			List<Order> orders = orderService.listByStatus(loginUser.getId(), 5);
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
		//获取用户完成订单
		if(status == 6) {
			List<Order> orders = orderService.listByStatus(loginUser.getId(), 6);
			model.addAttribute("orders", orders);
			return "client/user/my_order";
		}
			
		return "";
	}
	
	//删除订单
	@RequestMapping(value="/delete", method=RequestMethod.PUT)
	public void deleteOrder(int cid, HttpSession session,HttpServletResponse resp, Model model) throws IOException {
		User loginUser = (User) session.getAttribute("loginUser");
		orderService.delete(cid);	
		session.removeAttribute("orderSuccess");
		session.setAttribute("orderSuccess",orderService.countByStatus(loginUser.getId(), 6));
		Writer out = null;
		try {
			out = resp.getWriter();
			out.write("yes");
		} finally {
			out.close();
		}
	}	
	
	//立即付款订单右边 	
@RequestMapping(value="/paynow/{orderid}", method=RequestMethod.GET)
	public String delete(@PathVariable int orderid, Model model, HttpSession session) {
		Order order=orderService.load(orderid);
		model.addAttribute("order", order);
		User loginUser = (User) session.getAttribute("loginUser");
		int waitPay = orderService.countByStatus(loginUser.getId(), 1);	
		
		session.removeAttribute("waitPay");
		if(waitPay > 0) {
			session.setAttribute("waitPay", waitPay);
		}	
		return "client/user/pay";
	}

	/**
	 *	 
	 *	 取消订单
	 */
@RequestMapping(value="/cancel", method=RequestMethod.PUT)
public void cancelOrder(int cid, HttpSession session,HttpServletResponse resp, Model model) throws IOException {
	
	orderService.cancel(cid);	
	User loginUser = (User) session.getAttribute("loginUser");
	//获取用户所有订单
		//获取未付款订单数量
		int waitPay = orderService.countByStatus(loginUser.getId(), 1);	
		session.removeAttribute("waitPay");
		if(waitPay > 0) {
			session.setAttribute("waitPay", waitPay);
		}
	Writer out = null;
	try {
		out = resp.getWriter();
		out.write("yes");
	} finally {
		out.close();
	}
}	

	/**
	 * 搜索订单
	 *
	 */
@RequestMapping(value = "/search", method = RequestMethod.POST)
public String searchOrder(String name,int uid,Model model) throws IOException {
		List<Order> orders = orderService.listSearch(name, uid);
		model.addAttribute("orders",orders );
		model.addAttribute("name", name);
		return   "client/user/my_order";
		
	}
	
	/**
	 * 确认收货区  申请退款 状态
	 * 
	 **/
@RequestMapping(value = "/confirmShopping", method = RequestMethod.PUT)
public void confirmOrder( int orderid,int status,Model model, HttpSession session,HttpServletResponse resp) throws IOException {	
		Order order=orderService.load(orderid);
		User loginUser = (User) session.getAttribute("loginUser");
		order.setStatus(status);	
		orderService.update(order);	
		List<Order> orders = orderService.listByStatus(loginUser.getId(), status);
		model.addAttribute("orders", orders);
	
		if(status==6) {	
			session.removeAttribute("waitConfirm");		
			session.setAttribute("waitConfirm",orderService.countByStatus(loginUser.getId(), 3));
			session.removeAttribute("orderSuccess");
			session.setAttribute("orderSuccess",orderService.countByStatus(loginUser.getId(), 6));
			Writer out = null;
			try {
				out = resp.getWriter();
				out.write("yes");
			} finally {
				out.close();
			}
		}
		else
		{	session.removeAttribute("waitSend");
			session.setAttribute("waitSend", orderService.countByStatus(loginUser.getId(), 2));
			session.removeAttribute("refund");
			session.setAttribute("refund", orderService.countByStatus(loginUser.getId(), 4));
			Writer out = null;
			try {
				out = resp.getWriter();
				out.write("yes");
			} finally {
				out.close();
			}
		}
		
	
}
@RequestMapping(value = "/orderdeatil/{orderid}", method = RequestMethod.GET)	
public String orderDeatil(@PathVariable int orderid,Model model, HttpSession session) throws IOException {
		Order order=orderService.load(orderid);
		Address address=addressService.load(order.getAddress().getId()); 
		model.addAttribute("order", order);
		model.addAttribute("address", address);	
		return "client/user/my_order_deatil";	
}


/***
 * 
 * 立即购买pay跳转
 */
@RequestMapping(value="/create_order_now", method=RequestMethod.POST)
public String createOrderNow(Integer pid, int quanties, double price,int aid, String base, String place, 
		String name, String phone, HttpSession session, Model model) {
	User loginUser = (User) session.getAttribute("loginUser");
	//判断用户是否登录
	if(loginUser == null) {
		return "redirect:/user/login";
	}
	Address address = null;
	//如果是新添加的地址,保存到数据库中
	if(base != null && place != null && name != null && phone != null) {
		address = new Address(base, place, name, phone, 1, loginUser);
		addressService.add(address);
	}
	else {
		addressService.add(address);
		address = addressService.load(aid);
	}
	//新创建的订单是"未付款"状态
	int status = 1;
	//新创建的订单是"未删除"状态
	int isdel = 1;
	//获取系统时间
	Date d = new Date();
	//格式化时间
	String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
	//时间转换
	Timestamp date = Timestamp.valueOf(nowTime);
	//创建订单
	Order order = new Order(price, status, isdel, date, address, loginUser);
	//保存订单
	orderService.add(order);
	//获取所有的购物车id
	/*String carts[] = cids.split(",");*/
	/**
	 * 由于第一个存放在数组中的第一个值为空,因此舍弃数组中的第一个元素
	 */
/*		for(int i = 1; i < carts.length; i++) {
		//获取购物车记录
		Cart cart = cartService.load(Integer.parseInt(carts[i]));
		//获取购物车中的商品
		Product product = cart.getProduct();
		//创建订单商品关系
		OrderProduct orderProduct = new OrderProduct(cart.getQuantity(), order, product);
		//保存订单与商品关系
		orderProductService.add(orderProduct);
		//删除购物车中的记录
		cartService.delete(Integer.parseInt(carts[i]));
		//获取登录用户的购物车中商品种类数量
		int cartSize = cartService.cartSize(loginUser.getId());
		session.setAttribute("cartSize", cartSize); 
	}*/
	
	Product product = productService.productItem(pid);
	
	//创建订单商品关系
	OrderProduct orderProduct = new OrderProduct(quanties , order, product);
	orderProductService.add(orderProduct);
	//获取数据库中订单详细信息
	Order o = orderService.load(order.getId());
	model.addAttribute(o);
	return "client/user/pay";
}







}	
	
	
	
	
	

